<template>
  <div class="map-wrapper">
    <div id="amap">
      <div class="emerg-box">
        <div
          class="item"
          id="random-zoom-btn"
          v-for="(item, index) in TYPE.types"
          :key="index"
          @click="handleRandomZoom(index)"
        >
          <div class="img"><img :src="getImageUrl(item.url)" alt="" /></div>
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup >
import { onMounted, ref, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: "9ff8122f8b13991026e890ad326e8e38",
};

import TYPE from "../utils/types";
console.log(TYPE, "1111");
// 适用于Vite的图片路径解析函数
const getImageUrl = (name) => {
  return new URL(`../assets/command/${name}`, import.meta.url).href;
};
onUnmounted(() => {
  map.destroy();
});

// 配置部分
const mapConfig = {
  key: "f04a2a00725c91966cb0151e8c6989b8",
  version: "2.0",
  plugins: [
    "AMap.Geolocation",
    "AMap.GeoBoundary",
    "AMap.Scale",
    "AMap.ControlBar",
    "AMap.ToolBar",
    "AMap.HawkEye",
    "AMap.Compass",
    "AMap.MapType",
    "AMap.PlaceSearch",
    "AMap.DistrictSearch",
    "AMap.Geocoder",
    "AMap.MarkerClusterer",
    "AMap.PolyEditor",
    "AMap.CircleEditor",
    "AMap.PolygonEditor",
    "AMap.PolylineEditor",
    "AMap.RectangleEditor",
    "AMap.GeoJSON",
    "AMap.AMPixel",
    "AMap.sAMPoverlay",
  ],
};

const mapOptions = {
  mapStyle: "amap://styles/darkblue",
  zoom: 12,
  resizeEnable: true,
  center: [120.090113, 30.319728],
  viewMode: "3D",
  pitch: 20.5,
  showBuildingBlock: true,
  showIndoorMap: false, //关闭室内地图
  liteMode: true,
};
const map = ref(null);
// 初始化地图的函数
async function initMap() {
  try {
    const AMapl = await AMapLoader.load(mapConfig);

    map.value = createMap(AMapl);
    addDistrictBoundary(AMapl, map.value);

    addMapControls(AMapl, map.value);
    // handleRandomZoom(AMapl, map.value);
  } catch (error) {
    console.error("地图初始化失败:", error);
  }
}

// 创建地图实例的函数
function createMap(AMapl) {
  return new AMapl.Map("amap", mapOptions);
}

// 添加行政区边界的函数
function addDistrictBoundary(AMapl, map) {
  new AMapl.DistrictSearch({
    extensions: "all",
    subdistrict: 0,
  }).search("拱墅区", (status, result) => {
    if (status === "complete") {
      const outer = [
        new AMapl.LngLat(-360, 90, true),
        new AMapl.LngLat(-360, -90, true),
        new AMapl.LngLat(360, -90, true),
        new AMapl.LngLat(360, 90, true),
      ];

      const holes = result.districtList[0].boundaries;
      const pathArray = [outer, ...holes];
      const polygon = new AMapl.Polygon({
        path: pathArray,
        strokeColor: "#00eeff",
        strokeWeight: 2,
        fillColor: "#71B3ff",
        fillOpacity: 0.2,
      });
      polygon.setPath(pathArray);
      map.add(polygon);
    }
  });
}

// 添加地图控件的函数
function addMapControls(AMapl, map) {
  //  1.比例尺控件(左下角)
  const scale = new AMapl.Scale({
    position: "LB",
    offset: [10, 10],
  });
  map.addControl(scale);
  // //2.缩放控件(左上角)
  const zoomCtrl = new AMapl.ToolBar({
    position: {
      top: "10px",
      left: "10px",
    },
    offset: [10, 10],
  });
  map.addControl(zoomCtrl);
  // // //3.定位控件(右下角)
  const geolocation = new AMapl.Geolocation({
    position: "RB",
    showButtonWhentrue: true,
    offset: [10, 30],
  });
  map.addControl(geolocation);
  //4.ControlBar(3D专用控制栏) 指南针
  const controlBar = new AMapl.ControlBar({
    showControlButton: true,
    position: {
      right: "15px",
      top: "15px",
    },
  });
  map.addControl(controlBar);
  // /*=======可选高级功能=======*/
  // //5.鹰眼控件(右下角) 开启鹰眼控件，默认不显示 缩略图控件，默认不显示 鹰眼控件，默认不显示
  const overView = new AMapl.HawkEye({
    isOpen: true,
    offset: [10, 100],
  });
  map.addControl(overView);
  // //6.罗盘控件(右上角) 地图类型控件，默认显示地图、卫星图、3D视图切换按钮
  const compass = new AMapl.MapType({
    position: "RT",
    offset: [10, 120],
  });
  map.addControl(compass);
}

// 调用初始化函数
initMap();
// 随机缩放函数
const handleRandomZoom = async (index) => {
  if (!map.value) return;
  console.log("23123");

  // const zoom = Math.floor(Math.random() * 7) + 11; // zoom范围[11,18]
  // map.value.setZoom(zoom);
  // var lng = 120.190113 + Math.random() / 100; //经度范围[121.138398, 121.728226]
  // var lat = 30.319728 + Math.random() / 100; //纬度范围[30.972688, 31.487611]
  // map.value.setCenter([lng, lat]); //设置地图中心点
  // console.log(`当前层级已设为${zoom}级`);
  var markers0 = [
    {
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-1.png",
      position: [120.098113, 30.319728],
    },
    {
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-2.png",
      position: [120.090113, 30.319728],
    },
    {
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-3.png",
      position: [120.010113, 30.319728],
    },
  ];
  var markers1 = [
    {
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-1.png",
      position: [120.198113, 30.319728],
    },
    {
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-2.png",
      position: [120.290113, 30.319728],
    },
    {
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-3.png",
      position: [120.310113, 30.319728],
    },
  ];
  const x = await AMapLoader.load(mapConfig);

  if (index === 0) {
    markers0.forEach((m) => {
      new x.Marker({
        position: m.position, // [经度,纬度]
        title: "默认标记", // 鼠标悬停显示的文字
        map: map.value, // 绑定到地图实例
        // offset: new AMapl.Pixel(-13, -30), // 相对于标记左上角的偏移量，默认[0,-12]px
        // icon: m.icon,
      });
    });
    // map.value.clearMap();
    map.value.setFitView();
    // map.value.setZoom(13);
    // map.value.setCenter([120.198113, 30.319728]);
  } else if (index === 1) {
    markers1.forEach((m) => {
      new x.Marker({
        position: m.position, // [经度,纬度]
        title: "默认标记", // 鼠标悬停显示的文字
        map: map.value, // 绑定到地图实例
        // offset: new AMapl.Pixel(-13, -30), // 相对于标记左上角的偏移量，默认[0,-12]px
        // icon: m.icon,
      });
    });
    map.value.setFitView();
  }
};
</script>
<style lang='less' scoped>
.map-wrapper {
  width: 100%;
  height: 100vh;
  #amap {
    width: 100%;
    height: 100%;
    position: relative;
    .emerg-box {
      z-index: 999 !important;
      // opacity: 0.8;
      position: absolute;
      background-color: rgba(#122656, 0.9); /* 黑色背景50%透明度 */
      color: #8de7ff;
      left: 2%;
      top: 8%;
      width: 570px;
      height: 400px;
      padding: 1%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      align-content: flex-start;
      .item {
        cursor: pointer;
        width: 20%;
        height: 16%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        font-size: 12px;

        .img {
          width: 17%;
          height: 30%;
          margin-bottom: 7px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
}
</style>